package com.github.yoojia.mqtt.boot.utils;

import com.parkingwang.lang.SupplierThrow;
import com.parkingwang.lang.Try;
import com.parkingwang.lang.data.Config;
import com.parkingwang.lang.kit.StreamKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.Map;

/**
 * 配置加载器
 *
 * @author Yoojia Chen (yoojiachen@gmail.com)
 * @since 1.3
 */
public class ConfigKit {

    public static final Logger LOGGER = LoggerFactory.getLogger(ConfigKit.class);

    private ConfigKit() {
    }

    @SuppressWarnings("unchecked")
    public static Config stream(final InputStream stream) {
        return Try.die(new SupplierThrow<Config>() {
            @Override
            public Config call() throws Throwable {
                return new Config((Map<String, Object>) new Yaml().load(stream));
            }
        });
    }

    public static void extractByName(final String srcName, final String outputName) {
        final String dir = System.getProperty("user.dir");
        Try.die(new SupplierThrow<Boolean>() {
            @Override
            public Boolean call() throws Throwable {
                final File outputFile = Paths.get(dir, outputName).toFile();
                if (!outputFile.exists()) {
                    LOGGER.info("!!! FBI WARNING !!!");
                    LOGGER.info("A default config is extracting to path: {}", outputFile.getAbsolutePath());
                    StreamKit.copyAndClose(ConfigKit.class.getResourceAsStream(srcName),
                            new FileOutputStream(outputFile));
                }
                return true;
            }
        });
    }

}
